/*
 * Copyright (c) 2009, Jan Pastor. All Rights Reserved.
 */

package sk.jp.commons.utils;

import java.util.Locale;

/**
 * Utilities for <code>Locale</code> manipulation.
 *
 * @author Jan Pastor 
 */
public class LocaleUtils {

    private LocaleUtils() {
    }

    /**
     * Creates <code>Locale</code> instance from given full locale name.
     * <p>Full locale name is
     * the entire locale, with the language, country and variant separated by
     * underbars. Language is always lower case, and country is always upper case.
     * If the language is missing, the string will begin with an underbar. If both
     * the language and country fields are missing, this function will return the
     * empty string, even if the variant field is filled in (you can't have a locale
     * with just a variant-- the variant must accompany a valid language or country
     * code). Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC"
     * @param fullLocale
     * @return locale instance.
     * @throws NullPointerException if parameter <code>fullLocale</code> is null. 
     * @throws IllegalArgumentException if parameter <code>fullLocale</code> is empty.
     */
    public static Locale parseLocale(String fullLocale){
        if(fullLocale == null) throw new NullPointerException("Parameter fullLocale is null");
        if("".equals(fullLocale)) throw new IllegalArgumentException("Parameter fullLocale has empty value");

        String[] parts = fullLocale.split("_");
        switch (parts.length){
            case 1:
                return new Locale(parts[0]);
            case 2:
                return new Locale(parts[0], parts[1]);
            case 3:
                return new Locale(parts[0], parts[1], parts[2]);
            default:
                throw new IllegalArgumentException("Invalid format of fullLocale ('"+fullLocale+"')");
        }
    }

}
